<template>
  <div class="app-container flex flex-col flex-1 bg-[#efefef]">
    <div class="header-c rounded-[4px] bg-white p-4">
      <el-form ref="formRef" :model="form">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="小区名称:">
              <communitySelect
                v-model="form.communityId"
                @change="communityChangeHandle"
              />
            </el-form-item>
          </el-col>

          <el-col :span="6">
            <el-form-item label="小区地址:">
              <span>{{ form.communityAddress || "无" }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="小区负责人:">
              <span v-if="form.contactName">
                <template v-if="form.contactName">
                  {{ form.contactName }}
                </template>
                <template v-if="form.contactPhone">
                  ({{ form.contactPhone }})
                </template>
              </span>
              <span v-else>无</span>
            </el-form-item>
          </el-col>
          <el-col :span="6" v-if="form.communityId">
            <div class="mt-2 flex justify-end">
              <el-button type="primary" @click="goRoomList">房屋管理</el-button>
              <el-button type="primary" @click="goParkingList"
                >车位管理</el-button
              >
            </div>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <!-- 主内容区 -->
    <div class="flex mt-2 flex-1">
      <div
        class="bg-white rounded-[4px] mr-2 flex-shrink-0 py-2 px-4 mr-2 w-[240px] left-c"
      >
        <div class="py-2 mb-2 h-[40px] border-b text-[#333] flex items-center">
          <span class="text-[14px]">楼栋列表</span>
          <el-button
            v-if="form.communityId"
            class="ml-auto"
            type="text"
            size="small"
            @click="addBuildingHandle"
          >
            新增楼栋
          </el-button>
        </div>
        <div class="list-c px-2 h-full text-[#333]">
          <template v-if="floorList.length === 0">
            <el-empty description="暂无楼栋" image-size="100">
              <el-button
                type="primary"
                @click="addBuildingHandle"
                v-if="form.communityId"
                >新增楼栋</el-button
              >
            </el-empty>
          </template>
          <template v-else>
            <div
              v-for="item in floorList"
              :key="item.id"
              class="item-c flex items-center border-b-[1px] border-[#efefef] py-2"
              @click="floorChangeHandle(item)"
            >
              <div>{{ item.name }}</div>
              <div class="ml-auto text-[#666] text-[16px]">
                <el-icon @click.stop="editBuildingHandle(item)">
                  <Edit />
                </el-icon>
                <el-icon class="ml-2" @click.stop="deleteBuildingHandle(item)">
                  <Delete />
                </el-icon>
              </div>
            </div>
          </template>
        </div>
      </div>
      <!-- table宽度自适应问题, 需要给父级添加 overflow-x-hidden -->
      <div
        class="bg-white rounded-[4px] overflow-x-hidden flex-1 px-4 py-2 right-c flex flex-col"
      >
        <div class="py-2 h-[40px] text-[#333] w-full flex items-center">
          <span class="text-[14px]">楼层列表</span>
          <template v-if="curFloor.name">
            <div class="flex items-center text-[14px] text-[#999] ml-4">
              <span class="ml-3">楼栋:{{ curFloor.name }}</span>
              <span class="ml-3">朝向: {{ curFloor.floorOrientation }}</span>
              <span class="ml-3">楼高:{{ curFloor.height }}米</span>
              <span class="ml-3">楼层:{{ curFloor.floor }}层</span>
            </div>
            <div class="ml-auto">
              <el-button type="text" @click="addRoomHandle">新增房源</el-button>
            </div>
          </template>
        </div>
        <!-- 楼层 -->
        <div class="flex size-full">
          <el-table
            :data="tableData"
            :columns="tableColumns"
            style="width: 100%"
            border
          >
            <el-table-column
              v-for="item in tableColumns"
              :key="item.prop"
              header-align="center"
              align="center"
              :width="item.width"
              :min-width="item.minWidth"
              :prop="item.prop"
              :label="item.label"
              :formatter="item.formatter"
            >
              <template #default="{ row }" v-if="item.prop !== 'floor'">
                <div class="flex flex-wrap">
                  <div
                    v-for="room in row[item.prop] || []"
                    :key="room.id"
                    class="px-2 py-1 border rounded-[4px] mr-2 mb-2 flex items-center"
                  >
                    <div class="px-2">{{ room.roomNum }}</div>
                    <div class="flex flex-col">
                      <el-button
                        type="text"
                        size="small"
                        class="!ml-0 !p-0"
                        @click="detailHandle(room)"
                        >详情</el-button
                      >
                    </div>
                  </div>
                </div>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
    </div>
    <addEdit
      v-model="addEditVisible"
      v-if="addEditVisible"
      :row="curRow"
      :title="title"
      @submit="getFloorList"
      :communityId="form.communityId"
    />
    <roomAddEdit
      v-model="roomAddEditVisible"
      v-model:isDetail="isDetail"
      v-if="roomAddEditVisible"
      :row="curRow"
      :building="curFloor"
      :title="title"
      @submit="floorChangeHandle(curFloor)"
      :communityId="form.communityId"
    />
  </div>
</template>

<script setup name="building">
import { ref, getCurrentInstance, reactive, computed } from "vue";
import { useRouter } from "vue-router";
import {
  getFloorPage,
  getBuildingRoomPage,
  removeFloor,
} from "@/api/realEstateManage";
import addEdit from "./addEdit";
import roomAddEdit from "./roomAddEdit";
import { Edit, Delete } from "@element-plus/icons-vue";
import communitySelect from "@/components/communitySelect";
const { proxy } = getCurrentInstance();

const router = useRouter();
const form = reactive({
  communityId: "",
  communityAddress: "",
  contactName: "",
  contactPhone: "",
});

const title = ref("");
const addEditVisible = ref(false);
const floorList = ref([]); // 楼栋列表
const curFloor = ref({}); // 当前楼栋

const tableData = ref([]); // 楼层数据
const tableColumns = ref([]); // 单元
// =============楼栋相关逻辑=============
// 根据当前选择的楼栋的单元数，计算出每一列的col span， 确保只在一行展示
// const colSpan = computed(() => {
//   const unitCount = curFloor.value?.totalUnitNum || 1;
//   return 24 / unitCount;
// });
const floorChangeHandle = async (item) => {
  curFloor.value = item;
  tableData.value = [];
  tableColumns.value = [
    {
      label: "楼层",
      prop: "floor",
      width: 100,
      formatter: (row) => {
        return `${row.floor}楼`;
      },
    },
  ];
  for (let i = 1; i <= Number(item.totalUnitNum || 0); i++) {
    tableColumns.value.push({
      label: `${i}单元`,
      prop: `unit${i}`,
      minWidth: 100,
    });
  }
  const roomList = await getRoomList();
  for (let i = Number(item.floor || 0); i >= 1; i--) {
    let data = {
      floor: i,
    };
    for (let j = 1; j <= Number(item.totalUnitNum || 0); j++) {
      data[`unit${j}`] = roomList.filter(
        (item) => item.unitNum == j && item.layer == i
      );
    }
    tableData.value.push(data);
    console.log("[ data ] >", data);
  }

  // 获取房屋列表， 组合成符合ui展示的结构
};
const getFloorList = () => {
  if (!form.communityId) {
    return;
  }
  getFloorPage({
    communityId: form.communityId,
    pageNo: 1,
    pageSize: 1000,
  }).then(({ data }) => {
    floorList.value = data.records;
    curFloor.value = {};
  });
};
const communityChangeHandle = (id, community) => {
  form.communityId = id;
  form.communityAddress =
    community.fullAddress ||
    `${community.province} ${community.city} ${community.area} ${community.address}`;
  form.contactName = community.contactName;
  form.contactPhone = community.contactPhone;
  getFloorList();
  tableData.value = [];
};

// 新增楼栋
const addBuildingHandle = () => {
  addEditVisible.value = true;
  curRow.value = {};
  title.value = "新增楼栋";
  getFloorList();
};

const curRow = ref({});
// 编辑楼栋
const editBuildingHandle = (item) => {
  curRow.value = item;
  title.value = "编辑楼栋";
  addEditVisible.value = true;
};
const deleteBuildingHandle = (item) => {
  removeFloor({ id: item.id }).then(({ data }) => {
    if (data) {
      proxy.$modal.msgSuccess("删除成功");
      getFloorList();
    } else {
      proxy.$modal.msgError("删除失败");
    }
  });
};

// =============房屋相关逻辑=============
const roomAddEditVisible = ref(false);
const roomList = ref([]);
const isDetail = ref(false);
const getRoomList = async () => {
  const { data } = await getBuildingRoomPage({
    floorId: curFloor.value.id,
    communityId: form.communityId,
    pageNo: 1,
    pageSize: 9999,
  });
  roomList.value = data.records || [];
  return roomList.value;
};

// 新增房源
const addRoomHandle = () => {
  roomAddEditVisible.value = true;
  curRow.value = {};
  title.value = "新增房源";
  isDetail.value = false;
};
const detailHandle = (item) => {
  roomAddEditVisible.value = true;
  curRow.value = item;
  title.value = "查看房源";
  isDetail.value = true;
};

const goRoomList = () => {
  router.push("/realEstateManage/roomList");
};
const goParkingList = () => {
  router.push("/realEstateManage/parkingSpace");
};
</script>

<style scoped lang="scss">
.el-form {
  .el-input,
  .el-cascader {
    width: 100%;
  }
}
</style>
